package com.onlinelearn.chatservice.service;

import com.onlinelearn.chatservice.dto.MessageDTO;
import com.onlinelearn.chatservice.model.Message;
import com.onlinelearn.chatservice.model.MessageType;
import com.onlinelearn.chatservice.repository.MessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessageService {
    @Autowired
    private MessageRepository messageRepository;

    public MessageDTO sendMessage(MessageDTO messageDTO) {
        Message message = convertToEntity(messageDTO);
        Message savedMessage = messageRepository.save(message);
        return convertToDTO(savedMessage);
    }

    public List<MessageDTO> getUnreadMessages(Long chatRoomId) {
        List<Message> unreadMessages = messageRepository.findByChatRoomIdAndIsReadFalse(chatRoomId);
        return unreadMessages.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    public void markMessageAsRead(Long messageId) {
        Message message = messageRepository.findById(messageId)
                .orElseThrow(() -> new RuntimeException("消息未找到"));
        message.setIsRead(true);
        messageRepository.save(message);
    }

    public List<MessageDTO> filterContent(List<MessageDTO> messages) {
        return messages.stream()
                .filter(this::isContentAllowed)
                .collect(Collectors.toList());
    }

    private boolean isContentAllowed(MessageDTO message) {
        // 敏感词过滤逻辑
        String[] sensitiveWords = {"广告", "垃圾信息"};
        return !containsSensitiveWords(message.getContent(), sensitiveWords);
    }

    private boolean containsSensitiveWords(String content, String[] sensitiveWords) {
        for (String word : sensitiveWords) {
            if (content.contains(word)) {
                return true;
            }
        }
        return false;
    }

    private Message convertToEntity(MessageDTO dto) {
        Message message = new Message();
        message.setSenderId(dto.getSenderId());
        message.setReceiverId(dto.getReceiverId());
        message.setContent(dto.getContent());
        message.setType(dto.getType());
        return message;
    }

    private MessageDTO convertToDTO(Message message) {
        MessageDTO dto = new MessageDTO();
        dto.setId(message.getId());
        dto.setSenderId(message.getSenderId());
        dto.setReceiverId(message.getReceiverId());
        dto.setContent(message.getContent());
        dto.setType(message.getType());
        dto.setTimestamp(message.getTimestamp());
        dto.setIsRead(message.getIsRead());
        return dto;
    }
} 